<template>
  <div>
    <!--面包屑导航-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!--contain-->
    <el-card>
      <!--Tips-->
      <el-alert title="注意：只允许为第三级分类设置相关参数！" type="warning" show-icon></el-alert>
      <el-row>
        <el-col :span="24">
          <span>选择商品分类：</span>
          <el-cascader
            v-model="cateValue"
            :options="cateList"
            :props="cateProps"
            @change="cateListChange"
          ></el-cascader>
        </el-col>
      </el-row>
      <el-tabs v-model="attrActive" @tab-click="cateAttrClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            size="small"
            :disabled="isButtonDis"
            @click="addAttrVisible=true"
          >添加参数</el-button>
          <el-table :data="attrTable" border style="width: 100%">
            <el-table-column type="expand">
              <template v-slot:default="scope">
                <el-tag
                  v-for="(item,i) in attrVals(scope.row)"
                  :key="i"
                  closable
                  @close="tagClose(i,scope.row)"
                >{{item}}</el-tag>
                <el-input
                  v-if="scope.row.tagInputVisible"
                  v-model="scope.row.tagInputValue"
                  class="input-new-tag"
                  size="small"
                  ref="saveTagInput"
                  @keyup.enter.native="confirmTagInput(scope.row)"
                  @blur="confirmTagInput(scope.row)"
                ></el-input>
                <el-button size="small" v-else @click="showTagInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作" width="200">
              <template v-slot:default="scope">
                <el-button type="primary" size="small" @click="showEditAttr(scope.row)">编辑</el-button>
                <el-button type="danger" size="small" @click="deleteEditAttr(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            size="small"
            :disabled="isButtonDis"
            @click="addAttrVisible=true"
          >添加属性</el-button>
          <el-table :data="attrTable" border style="width: 100%">
            <el-table-column type="expand">
              <template v-slot:default="scope">
                <el-tag
                  v-for="(item,i) in attrVals(scope.row)"
                  :key="i"
                  closable
                  @close="tagClose(i,scope.row)"
                >{{item}}</el-tag>
                <el-input
                  v-if="scope.row.tagInputVisible"
                  v-model="scope.row.tagInputValue"
                  class="input-new-tag"
                  size="small"
                  ref="saveTagInput"
                  @keyup.enter.native="confirmTagInput(scope.row)"
                  @blur="confirmTagInput(scope.row)"
                ></el-input>
                <el-button size="small" v-else @click="showTagInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="属性名称"></el-table-column>
            <el-table-column label="操作" width="200">
              <template v-slot:default="scope">
                <el-button type="primary" size="small" @click="showEditAttr(scope.row)">编辑</el-button>
                <el-button type="danger" size="small" @click="deleteEditAttr(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!--添加参数对话框-->
    <el-dialog
      :title="'添加'+addTitle"
      :visible.sync="addAttrVisible"
      width="50%"
      @closed="resetAddAttrForm"
    >
      <el-form ref="addAttrRef" :model="addAttrForm" :rules="addAttrRules" label-width="80px">
        <el-form-item :label="addTitle" prop="attr_name">
          <el-input v-model="addAttrForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addAttrVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmAddAttr">确 定</el-button>
      </span>
    </el-dialog>
    <!--编辑参数对话框-->
    <el-dialog
      :title="'编辑'+addTitle"
      :visible.sync="editAttrVisible"
      width="50%"
      @closed="resetEditAttrForm"
    >
      <el-form ref="editAttrRef" :model="editAttrForm" :rules="editAttrRules" label-width="80px">
        <el-form-item :label="addTitle" prop="attr_name">
          <el-input v-model="editAttrForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editAttrVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmEditAttr">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      cateList: [],
      cateValue: null,
      isButtonDis: true,
      // 层级列表props配置
      cateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover'
      },
      attrActive: 'many',
      // 属性表格
      attrTable: [],
      // 添加参数
      addAttrVisible: false,
      addAttrForm: {
        attr_name: ''
      },
      addAttrRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
          { min: 1, max: 20, message: '名称长度在1到20之间', trigger: 'blur' }
        ]
      },
      // 编辑参数
      editAttrVisible: false,
      editAttrForm: {
        attr_name: ''
      },
      editAttrRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
          { min: 1, max: 20, message: '名称长度在1到20之间', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    // 获取商品分类列表
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('商品分类列表获取失败！')
      }
      this.cateList = res.data
    },
    // 监听cascader值，获取children分类id
    cateListChange(value) {
      if (value.length === 3) {
        this.cateValue = value[value.length - 1]
        if (this.cateValue) {
          this.isButtonDis = false
        }
      } else {
        this.isButtonDis = true
      }
      this.getCateAttrList()
    },
    // 获取商品参数列表
    async getCateAttrList() {
      if (this.cateValue) {
        const { data: res } = await this.$http.get(
          `categories/${this.cateValue}/attributes`,
          {
            params: {
              sel: this.attrActive
            }
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('获取商品参数失败！')
        }
        res.data.forEach(item => {
          item.tagInputVisible = false
          item.tagInputValue = ''
        })
        this.attrTable = res.data
      }
    },
    // tabs点击事件
    cateAttrClick() {
      this.getCateAttrList()
    },
    showTagInput(row) {
      row.tagInputVisible = true
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 添加参数属性标签
    confirmTagInput(row) {
      if (row.tagInputValue) {
        // 判断参数属性值是否为空
        if (!row.attr_vals) {
          row.attr_vals += row.tagInputValue.trim()
        } else {
          row.attr_vals += ',' + row.tagInputValue.trim()
        }
        this.saveAttrVals(row)
      }
      row.tagInputVisible = false
      row.tagInputValue = ''
    },
    // 添加参数
    confirmAddAttr() {
      this.$refs.addAttrRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post(
          `categories/${this.cateValue}/attributes`,
          {
            attr_name: this.addAttrForm.attr_name,
            attr_sel: this.attrActive
          }
        )
        if (res.meta.status !== 201) {
          return this.$message.error('添加属性失败！')
        }
        this.getCateAttrList()
        this.addAttrVisible = false
      })
    },
    resetAddAttrForm() {
      this.$refs.addAttrRef.resetFields()
    },
    // 编辑参数
    async showEditAttr(row) {
      this.editAttrVisible = true
      const { data: res } = await this.$http.get(`categories/${row.cat_id}/attributes/${row.attr_id}`, {
        params: {
          attr_sel: this.attrActive
        }
      })
      if (res.meta.status !== 200) return this.$message.error('获取参数数据失败！')
      this.editAttrForm = res.data
    },
    // 提交修改的参数名称
    confirmEditAttr() {
      this.$refs.editAttrRef.validate(async valid => {
        if (!valid) return false
        const { data: res } = await this.$http.put(`categories/${this.cateValue}/attributes/${this.editAttrForm.attr_id}`, {
          attr_name: this.editAttrForm.attr_name,
          attr_sel: this.editAttrForm.attr_sel,
          attr_vals: this.editAttrForm.attr_vals
        })
        if (res.meta.status !== 200) return this.$message.error('编辑参数失败！')
        this.getCateAttrList()
        this.editAttrVisible = false
      })
    },
    resetEditAttrForm() {
      this.$refs.editAttrRef.resetFields()
    },
    // 删除商品参数
    deleteEditAttr(row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete(`categories/${row.cat_id}/attributes/${row.attr_id}`)
        if (res.meta.status !== 200) return this.$message.error('删除失败!')
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        this.getCateAttrList()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 提交参数标签到数据库
    async saveAttrVals(row) {
      const { data: res } = await this.$http.put(
        `categories/${this.cateValue}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('修改参数项失败！')
      }
      this.$message.success('修改参数项成功！')
    },

    // 删除参数属性标签
    tagClose(i, row) {
      const attrvalArr = row.attr_vals.split(',')
      attrvalArr.splice(i, 1)
      row.attr_vals = attrvalArr.join(',')
      this.saveAttrVals(row)
    },
    // 过滤字符串为空的参数标签
    attrVals(row) {
      if (row.attr_vals === '') {
        return []
      } else {
        return row.attr_vals.split(',')
      }
    }
  },
  computed: {
    // 添加参数对话框标题判断
    addTitle() {
      if (this.attrActive === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    }
  }
}
</script>

<style lang="less" scoped>
.el-cascader {
  margin: 15px 0;
}
.el-tag {
  margin: 6px;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
}
.el-button {
  margin-left: 6px;
}
</style>
